package com.itheima.health.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.health.constants.MessageConstant;
import com.itheima.health.entity.PageResult;
import com.itheima.health.entity.QueryPageBean;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.Permission;
import com.itheima.health.service.PermissionService;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @ClassName CheckItemController
 * @Description TODO
 * @Author ly
 * @Company 深圳黑马程序员
 * @Date 2019/9/11 9:57
 * @Version V1.0
 */
@RestController // json响应
@RequestMapping(value = "/permission")
public class PermissionController {

    @Reference
    PermissionService permissionService;

    @RequestMapping("/selectPage")
    public PageResult selectPage(@RequestBody QueryPageBean queryPageBean) {
        PageResult pageResult = permissionService.pageQuery(
                //传递当前页, 每页显示的记录数, 查询条件
                //响应PageResult, 封装总记录数, 结果集
                queryPageBean.getCurrentPage(),
                queryPageBean.getQueryString(),
                queryPageBean.getPageSize()
        );

        return pageResult;
    }

    @RequestMapping("/add")
    public Result add(@RequestBody Permission permission, List<Integer> roleIds) {
        try {
            permissionService.add(permission, roleIds);
        } catch (Exception e) {
            return new Result(false, MessageConstant.FAIL);
        }

        return new Result(true, MessageConstant.SUCCESS);

    }

    @RequestMapping("/update")
    public Result update(@RequestBody Permission permission) {
        try {
            permissionService.update(permission);
        } catch (Exception e) {
            return new Result(false, MessageConstant.FAIL);
        }

        return new Result(true, MessageConstant.SUCCESS);

    }

    @RequestMapping("/selectById")
    public Result selectById(Integer id) {
        Permission permission = permissionService.findById(id);
        if(permission != null){
            Result result = new Result(true, MessageConstant.SUCCESS,permission);
            return result;
        }
        return new Result(false,MessageConstant.FAIL);
    }

    @RequestMapping("/selectAll")
    public List<Permission> selectAll() {
        List<Permission> list = permissionService.selectAll();

        return list;
    }

    @RequestMapping("/delete")
    public Result delete(Integer id) {
        try {
            permissionService.delete(id);
            return new Result(true, MessageConstant.SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.FAIL);
        }
    }

}
